package com.trt.beibei.service;

import com.trt.beibei.model.Spu;
import com.trt.beibei.repository.SpuRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

@Service
public class SpuService {

    @Autowired
    private SpuRepository spuRepository;

    public Spu getSpu(Long id) {
        return spuRepository.findOneById(id);
    }

//    public List<Spu> getLatestPagingSpu() {
//        return spuRepository.findAll();
//    }

    public Page<Spu> getLatestPagingSpu(Integer pageNum, Integer size) {
        Pageable page = PageRequest.of(pageNum, size, Sort.by("createTime").descending());
        return spuRepository.findAll(page);
    }

    public Page<Spu> getByCategory(Long cid, Boolean isRoot, Integer pageNum, Integer size) {
        Pageable page = PageRequest.of(pageNum, size);
        if(isRoot){
            return spuRepository.findByRootCategoryIdOrderByCreateTime(cid, page);
        }
        else{
            return spuRepository.findByCategoryIdOrderByCreateTimeDesc(cid, page);
        }
    }
}
